package peng.yang.express.Activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import peng.yang.express.Adapter.CheckBaseAdapter;
import peng.yang.express.Bean.ExpressMember;
import peng.yang.express.Bean.PhoneRequest;
import peng.yang.express.R;
import peng.yang.express.Util.HistoryMembersDao;
import peng.yang.express.Util.NetWork;
import peng.yang.express.Util.PhoneMembersDao;
import peng.yang.express.VolleyUtils.JsonArrayToListcheck;
import peng.yang.express.VolleyUtils.RequestQueueUtils;

public class CheckActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG = "CheckActivity ";

    private ImageView check_image;
    private TextView check_name;
    private TextView check_num;
    private ListView checklist;
    private Button refresh;
    private String com;
    private String nu;
    private String url;

    private List<PhoneRequest> sourcelist;
    private String goodName;
    private PhoneMembersDao membersDao;
    private LinearLayout layout01;
    private LinearLayout layout02;
    private LinearLayout layout03;
    private RelativeLayout waite;
    private ImageView waite1;
    private RelativeLayout error;

/*    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    layout02.setVisibility(View.INVISIBLE);
                    layout01.setVisibility(View.VISIBLE);
                    waite.setVisibility(View.INVISIBLE);
                    break;
            }

        }
    };*/


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check);

        initView();
        initData();
        getData();

    }

    /**
     * 初始化组件
     */
    private void initView() {
        check_image = (ImageView) findViewById(R.id.riv_check_image);
        check_name = (TextView) findViewById(R.id.tv_check_name);
        check_num = (TextView) findViewById(R.id.tv_check_num);
        checklist = (ListView) findViewById(R.id.lv_check);
        layout01 = (LinearLayout) findViewById(R.id.check01);
        layout02 = (LinearLayout) findViewById(R.id.check02);
        waite = (RelativeLayout) findViewById(R.id.waite);
        error = (RelativeLayout) findViewById(R.id.error);
        waite1 = (ImageView) findViewById(R.id.waite1);

        refresh = (Button) findViewById(R.id.refresh);
        refresh.setOnClickListener(this);

    }

    /**
     * 初始化数据
     */
    private void initData() {
        /**
         * intent 带过来的数据
         * 1、fragment1带回的数据
         * 2、查询历史带回的数据
         */
        Intent intent = getIntent();
        com = intent.getStringExtra("com");
        nu = intent.getStringExtra("nu");
        goodName = intent.getStringExtra("goodName");
        /**
         *查询数据库  取得标题的头像
         * 并设置标题的文本
         */
        membersDao = new PhoneMembersDao(CheckActivity.this);
        String path = membersDao.queryExpress(com).getFileImagePath();
        File file = new File(this.getFilesDir(), path);
        Bitmap bitmap1 = BitmapFactory.decodeFile(file.getAbsolutePath());
        check_image.setImageBitmap(bitmap1);
        check_name.setText(membersDao.queryExpress(com).getExpName().toString());
        check_num.setText(nu);
    }

    public void getData() {

        if (NetWork.getNetWorkInfo(this)) {
            layout02.setVisibility(View.INVISIBLE);
            layout01.setVisibility(View.INVISIBLE);
            waite.setVisibility(View.VISIBLE);
            error.setVisibility(View.INVISIBLE);
            Animation animation = AnimationUtils.loadAnimation(this,
                    R.anim.rotate);
            waite1.startAnimation(animation);
            //请求网络数据
            requestData();

        } else {

            layout02.setVisibility(View.VISIBLE);
            layout01.setVisibility(View.INVISIBLE);
            waite.setVisibility(View.INVISIBLE);
            error.setVisibility(View.INVISIBLE);
        }
    }

    private void requestData() {
        url = "http://route.showapi.com/64-19?showapi_appid=20075&showapi_sign=a40bc8ce822d42b585b28d5b39cb9953&com=" + com + "&nu=" + nu;
        RequestQueueUtils.exectueJsonRequest(this, url.trim(), new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject jsonObject) {
                try {

                    JSONObject jsonObject1 = jsonObject.getJSONObject("showapi_res_body");
                    JSONArray jsonArray = jsonObject1.getJSONArray("data");

                    JsonArrayToListcheck toList = new JsonArrayToListcheck(jsonArray);
                    sourcelist = toList.setJRToList();
                    if (sourcelist.size() != 0) {
                        layout02.setVisibility(View.INVISIBLE);
                        layout01.setVisibility(View.VISIBLE);
                        waite.setVisibility(View.INVISIBLE);
                        error.setVisibility(View.INVISIBLE);
                        CheckBaseAdapter adapter = new CheckBaseAdapter(CheckActivity.this, sourcelist);
                        checklist.setAdapter(adapter);
                        dataBaseInstall();
                    } else {
                        layout02.setVisibility(View.INVISIBLE);
                        layout01.setVisibility(View.INVISIBLE);
                        waite.setVisibility(View.INVISIBLE);
                        error.setVisibility(View.VISIBLE);
                    }

                } catch (JSONException e) {
                    layout02.setVisibility(View.INVISIBLE);
                    layout01.setVisibility(View.INVISIBLE);
                    waite.setVisibility(View.INVISIBLE);
                    error.setVisibility(View.VISIBLE);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                layout02.setVisibility(View.INVISIBLE);
                layout01.setVisibility(View.INVISIBLE);
                waite.setVisibility(View.INVISIBLE);
                error.setVisibility(View.VISIBLE);
            }
        });
    }

    public void dataBaseInstall() {


        HistoryMembersDao historyMembersDao = new HistoryMembersDao(CheckActivity.this);
        List<ExpressMember> memberList = historyMembersDao.getAllMembers();
        List<String> nums = new ArrayList<>();
        for (int i = 0; i < memberList.size(); i++) {
            nums.add(memberList.get(i).getNum());
        }

        if (!nums.contains(nu)) {
            ExpressMember expressMember = new ExpressMember();
            expressMember.setNum(nu);
            expressMember.setExpName(membersDao.queryExpress(com).getExpName());
            expressMember.setState(sourcelist.get(0).getState() + sourcelist.get(0).getTime());
            expressMember.setFileImageUrl(membersDao.queryExpress(com).getFileImagePath());
            Log.e(TAG + "path", membersDao.queryExpress(com).getFileImagePath());
            expressMember.setGoodname(goodName);
            historyMembersDao.insert(expressMember);
        } else {
            historyMembersDao.update(nu, sourcelist);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.refresh:
                getData();
                break;
        }
    }
}
